<template>
  <div class="overflow-hidden px-10">
    <div class="head-title">企业信息</div>
    <div class="form-content">
      <el-form
        ref="enterpriseForm"
        :model="enterpriseForm"
        label-width="9rem"
        :rules="formRules"
      >
        <div class="form-sub-title">基本信息</div>
        <div class="w-full flex content-center flex-wrap pr-24 justify-switch">
          <el-form-item
            label="企业名称:"
            class="fixed-input-w"
            prop="companyName"
          >
            <el-input
              v-model="enterpriseForm.companyName"
              readonly
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="统一社会信用代码:"
            class="fixed-input-w"
            prop="creditCode"
          >
            <el-input
              v-model="enterpriseForm.creditCode"
              readonly
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="注册地址:"
            class="fixed-input-w"
            prop="declareAddress"
          >
            <el-cascader
              v-model="area"
              :options="areaOptions"
              :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'childern',
              }"
              placeholder="请选择"
              clearable
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="企业性质:" class="fixed-input-w" prop="nature">
            <el-select
              v-model="enterpriseForm.nature"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in natureOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="办公地址:" class="fixed-input-w" prop="address">
            <el-input v-model="enterpriseForm.address"></el-input>
          </el-form-item>
          <el-form-item
            label="注册资金( 万元 ):"
            class="fixed-input-w"
            prop="registeredMoney"
          >
            <el-input
              type="age"
              v-model.number="enterpriseForm.registeredMoney"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="所属领域:"
            class="fixed-input-w"
            prop="registeredMoney"
          >
            <el-select
              v-model="enterpriseForm.fieldId"
              multiple
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="(item, index) in companyFieldList"
                :key="'fieldId' + index"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="实际资金:"
            class="fixed-input-w"
            prop="trueMoney"
          >
            <el-input
              type="age"
              v-model.number="enterpriseForm.trueMoney"
            ></el-input>
          </el-form-item>
        </div>

        <div class="form-sub-title">法人信息</div>
        <div class="w-full flex content-center flex-wrap pr-24 justify-switch">
          <el-form-item
            label="法人姓名:"
            class="fixed-input-w"
            prop="legalPerson"
          >
            <el-input v-model="enterpriseForm.legalPerson"></el-input>
          </el-form-item>
          <el-form-item
            label="法人身份证号:"
            class="fixed-input-w"
            prop="legalPersonCode"
          >
            <el-input v-model="enterpriseForm.legalPersonCode"></el-input>
          </el-form-item>
          <el-form-item label="国籍:" class="fixed-input-w" prop="nationality">
            <el-select
              v-model="enterpriseForm.nationality"
              placeholder="无"
              style="width: 100%"
              clearable
              filterable
              size="small"
            >
              <el-option
                v-for="(item, index) in nationOptions"
                :key="item.name + index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号:" class="fixed-input-w" prop="legalPhone">
            <el-input v-model="enterpriseForm.legalPhone"></el-input>
          </el-form-item>
          <el-form-item
            label="联系电话:"
            class="fixed-input-w"
            prop="legalFixedPhone"
          >
            <el-input v-model="enterpriseForm.legalFixedPhone"></el-input>
          </el-form-item>
          <el-form-item
            label="邮政编码:"
            class="fixed-input-w"
            prop="legalPostCode"
          >
            <el-input v-model="enterpriseForm.legalPostCode"></el-input>
          </el-form-item>
          <el-form-item label="电子邮箱:" class="fixed-input-w" prop="email">
            <el-input v-model="enterpriseForm.email"></el-input>
          </el-form-item>
        </div>

        <el-row
          :gutter="24"
          class="w-2/3"
          style="margin: 0 auto; margin-top: 1rem"
        >
          <el-col :span="12">
            <el-button
              type="success"
              style="width: 100%"
              @click="linkTo('/policyDeclare')"
              >在线申报</el-button
            >
          </el-col>
          <el-col :span="12">
            <el-button type="primary" style="width: 100%" @click="onSubmit"
              >保存</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import SelectAddress from "@/components/SelectAddress";
import {
  getCompanyInfo,
  updateCompanyInfo,
} from "@/api/manageInformation/baseInfo";
import { getSpecificArea } from "@/api/system/user";
import { queryNationList } from "@/api/";

export default {
  name: "BaseInfo",
  components: {
    SelectAddress,
  },
  data() {
    // 表单校验数字使用
    var checkFormNumberV = (rule, value, callback) => {
      this.$emit("checkFormNumberV", rule, value, callback);
    };

    // 校验手机号
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error("请输入有效手机号"));
        } else {
          callback();
        }
      }, 1000);
    };

    // 校验三级联动下拉选
    var validateArea = (rule, value, callback) => {
      if (!value) {
        return callback();
      }

      this.$nextTick(() => {
        if (!this.area.length) {
          return callback(new Error("注册地址不能为空"));
        } else {
          return callback();
        }
      });
    };

    return {
      // 当前用户的公司id
      companyManagerId: undefined,

      // 当前是否可以进行修改
      isEdit: true,
      status: true,

      // 所属区域存储
      area: [],
      // 省市区三级联动选项
      areaOptions: [],

      // 表单
      enterpriseForm: {
        companyName: "",
        creditCode: "",
        registeredAddress: "",
        declareAddress: [],

        nature: "",
        address: "",
        registeredMoney: undefined,
        fieldId: undefined,
        trueMoney: undefined,

        legalPerson: "",
        legalPersonCode: "",
        nationality: 7,
        legalPhone: "",
        legalFixedPhone: "",
        legalPostCode: "",
        email: "",

        introduction: "",
      },

      // 企业规模
      scaleOptions: [],
      // 企业性质
      natureOptions: [],
      // 国籍列表
      nationOptions: [],
      // 所属领域
      companyFieldList: [],

      // 验证规则
      formRules: {
        companyName: [
          { required: true, message: "请输入企业名称", trigger: "blur" },
        ],
        // creditCode: [
        //   {
        //     required: true,
        //     message: "请输入社会统一信用代码",
        //     trigger: "blur",
        //   },
        // ],
        declareAddress: [{ required: true, validator: validateArea }],
        registeredMoney: [{ required: false, type: "number", trigger: "blur" }],
        trueMoney: [{ required: false, type: "number", trigger: "blur" }],
        legalPhone: [{ validator: checkPhone, trigger: "blur" }],
      },

      // 字典名
      dictNameList: [
        "declare_enterprise_natrue",
        "declare_enterprise_scale",
        "company_field",
      ],
    };
  },
  created() {
    this.initDictList();
    // 获取国籍列表
    queryNationList().then((res) => {
      this.nationOptions = res.data;
    });
  },
  mounted() {
    // 获取用户id
    this.companyManagerId = this.$store.state.user.companyId;

    // 获取到省市区信息以后 再开始赋值
    this.getSpecificAreaFun().then(() => {
      // 如果存在用户id则进行用户信息获取
      if (this.companyManagerId) {
        this.isEdit = true;
        getCompanyInfo(this.companyManagerId).then((res) => {
          this.enterpriseForm = JSON.parse(JSON.stringify(res.data));
          if (
            this.enterpriseForm.nationality == null ||
            this.enterpriseForm.nationality == undefined ||
            this.enterpriseForm.nationality == ""
          ) {
            this.enterpriseForm.nationality = 7;
          }
          this.enterpriseForm.nationality = Number(
            this.enterpriseForm.nationality
          );

          if (this.enterpriseForm.declareAddress) {
            // 将返回的数组重新转换为number类型 防止数据无法还原
            this.area = this.enterpriseForm.declareAddress
              .split(",")
              .map(Number);
          }

          // 回显所属领域
          if (this.enterpriseForm.fieldId) {
            this.enterpriseForm.fieldId =
              this.enterpriseForm.fieldId.split(",");
          }
        });
      } else {
        this.isEdit = false;
      }
    });
  },
  methods: {
    // 初始化所有字典类别
    initDictList() {
      this.getDicts(this.dictNameList[0]).then((res) => {
        if (res.code == 200) {
          this.natureOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[1]).then((res) => {
        if (res.code == 200) {
          this.scaleOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[2]).then((res) => {
        if (res.code == 200) {
          this.companyFieldList = res.data;
        }
      });
    },

    /* 查询省市区信息 */
    getSpecificAreaFun() {
      return new Promise((resolve, reject) => {
        getSpecificArea().then((res) => {
          this.areaOptions = [res.data];
          resolve();
        });
      });
    },
    // 省市区三级联动
    getRegiAddress(finalAddress) {},

    /* 根据省市区三级联动变化获取数据 */
    handleChange(value) {
      this.enterpriseForm.declareAddress = value;
    },
    /* END */

    // 页面跳转
    linkTo(path) {
      this.$router.push(path);
    },

    // 提交
    onSubmit() {
      this.$refs["enterpriseForm"].validate((valid) => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.enterpriseForm));
          obj.declareAddress = this.area ? this.area.join(",") : this.area;
          obj.fieldId = obj.fieldId ? obj.fieldId.join(",") : obj.fieldId;
          obj.area = undefined;
          updateCompanyInfo(JSON.stringify(obj)).then((response) => {
            this.isEdit = true;
            this.status = true;
            getCompanyInfo(this.companyManagerId).then((res) => {
              // console.log(res);
              this.enterpriseForm = res.data;
              // 回显地区
              this.area = this.enterpriseForm.declareAddress
                .split(",")
                .map(Number);
              // 回显国籍
              if (
                this.enterpriseForm.nationality == null ||
                this.enterpriseForm.nationality == undefined ||
                this.enterpriseForm.nationality == ""
              ) {
                this.enterpriseForm.nationality = 7;
              }
              this.enterpriseForm.nationality = Number(
                this.enterpriseForm.nationality
              );
              // 回显所属领域
              if (this.enterpriseForm.fieldId) {
                this.enterpriseForm.fieldId =
                  this.enterpriseForm.fieldId.split(",");
              }
              this.msgSuccess("修改成功");
            });
          });
        } else {
          this.msgError("有必填项还未填写，请重试！");
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.tag {
  @apply py-2 cursor-pointer px-4 mr-4 mb-2 rounded-md border;

  &:hover {
    @apply bg-blue-400 text-white;
  }
}

.fixed-input-w {
  ::v-deep input {
    @apply w-96;
  }
}

// 标题样式
.form-title {
  @apply text-center text-xl border-b p-3 mt-4;
}

// 标题样式
.head-title {
  position: relative;
  font-size: 20px;
  font-family: Source Han Sans CN, Source Han Sans CN-Bold;
  font-weight: bold;
  color: #1678ff;
  padding-left: 8px;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-48%);
    width: 4px;
    height: 1.25rem;
    background: #1678ff;
  }
}

// 内容样式
.form-content {
  .form-sub-title {
    @apply p-2 ml-0 mt-4 mb-8 text-xl border-b border-dashed border-gray-400;

    &:first-child {
      @apply mt-8;
    }
  }
}

/** 修改表单内无法修改时的样式 */
::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  // background-color: #fff;
  border-color: #dfe4ed;
  color: #333;
  /* border: 0; */
}

/* 当前如果是无法点击的状态修改表单的样式 */
.form-disabled {
  ::v-deep .el-input__inner {
    border: 0;
  }

  ::v-deep input::-webkit-input-placeholder,
  ::v-deep textarea::-webkit-input-placeholder,
  ::v-deep .el-cascader__search-input {
    color: #666;
  }

  ::v-deep input::-moz-input-placeholder,
  ::v-deep textarea::-moz-input-placeholder {
    color: #666;
  }

  ::v-deep input::-ms-input-placeholder,
  ::v-deep textarea::-ms-input-placeholder {
    color: #666;
  }

  ::v-deep .el-input__suffix {
    display: none;
  }

  ::v-deep .el-textarea__inner {
    margin-top: 0.2rem;
    border: 0;
    resize: none;
  }

  ::v-deep .el-upload {
    display: none;
  }

  .el-upload__tip {
    margin-left: 0.7rem;
    margin-top: 0.785rem;
  }
}

/** 媒体查询 */
.justify-switch {
  @apply justify-between;
}

@media screen and(max-width: 1680px) {
  /*<=1680的设备屏幕*/
  .justify-switch {
    @apply justify-center;
  }
}
</style>
